package com.sgb.kjwl.viewmodel.enterprise;

import android.content.Context;
import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.EnterpriseAPIManager;

import com.sgb.kjwl.model.entity.NeedDetailsEntity;
import com.sgb.kjwl.model.entity.ParentAreaMeasureEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.PointUtils;
import com.swgk.core.util.UserOperating;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddNeed_ServiceModel extends BaseViewModel {

    public MutableLiveData<String> name = new MutableLiveData<>();
    public MutableLiveData<String> service_class = new MutableLiveData<>();
    public MutableLiveData<Boolean> choice_team = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> choice_company = new MutableLiveData<>(false);
    public MutableLiveData<String> money = new MutableLiveData<>();
    public MutableLiveData<Boolean> is_bargaining = new MutableLiveData<>(false);
    public MutableLiveData<String> contacts_name = new MutableLiveData<>();
    public MutableLiveData<String> contacts_phone = new MutableLiveData<>();
    public MutableLiveData<String> need_content = new MutableLiveData<>();
    public MutableLiveData<String> need_remarks = new MutableLiveData<>();
    public MutableLiveData<String> toast_message = new MutableLiveData<>();
    public MutableLiveData<Integer> showloading_diag = new MutableLiveData<>();
    // 一级联动数据
    public List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> typeEntityList;
    // 二级联动数据
    public List<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<ParentAreaMeasureEntity>>> opt3 = new ArrayList<>();

    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> ldServiceCity = new MutableLiveData<>();
    public MutableLiveData<List<IpPickSelectEntity>> mBillTypeListLiveData = new MutableLiveData<>();
    public MutableLiveData<String> stringLiveData = new MutableLiveData<>();

    public int typePosition1;
    public int typePosition2;
    public int typePosition3;

    public String mServiceFirstNo;//服务分类No
    public String mServiceSecondNo;//服务类别No
    public String mServiceThirdNo;//服务类型区No

    public String mServiceFirstname;//服务分类No
    public String mServiceSecondname;//服务类别No
    public String mServiceThirdname;//服务类型区No

    public String provinceCode;//省编号
    public String provinceName;//省名称
    public String cityCode;
    public String cityName;
    public String areaCode;
    public String areaName;
    public String InvoiceRequirements;
    public String demandAttachment;

    public NeedDetailsEntity data = null;



    public MutableLiveData<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>> ldServiceType = new MutableLiveData<>(new ArrayList<>());


    public void subimtData(){


        if(TextUtils.isEmpty(name.getValue())){
            toast_message.postValue("请输入需求标题!");

            return;
        }
        if(TextUtils.isEmpty(service_class.getValue())){
            toast_message.postValue("请选择服务分类!");

            return;
        }


        if(!choice_team.getValue()&&!choice_company.getValue()){
            toast_message.postValue("请选择服务主体!");
            return;
        }

        if(TextUtils.isEmpty(money.getValue())&&!is_bargaining.getValue()){
            toast_message.postValue("请输入预算价格!");
            return;
        }

        if(TextUtils.isEmpty(contacts_name.getValue())){
            toast_message.postValue("请输入联系人姓名!");

            return;
        }

        if(TextUtils.isEmpty(contacts_phone.getValue())){
            toast_message.postValue("请输入联系电话!");
            return;
        }
        if (!CheckUtils.isMobileForService(contacts_phone.getValue())){
            toast_message.postValue("请输入正确的电话格式");
            return;
        }
        if(TextUtils.isEmpty(need_content.getValue())){

            toast_message.postValue("请输入需求说明内容");
            return;
        }

        Map<String,Object> map = new HashMap<>();
        map.put("demandTitle",name.getValue());



        map.put("categoryFirstId",mServiceFirstNo);
        map.put("categorySecondId",mServiceSecondNo);
        map.put("categoryThirdId",mServiceThirdNo);
        map.put("categoryFirstName",mServiceFirstname);
        map.put("categorySecondName",mServiceSecondname);
        map.put("categoryThirdName",mServiceThirdname);

        map.put("provinceCode",provinceCode);
        map.put("provinceName",provinceName);
        map.put("cityCode",cityCode);
        map.put("cityName",cityName);
        map.put("areaCode",areaCode);
        map.put("areaName",areaName);
        map.put("InvoiceRequirements",InvoiceRequirements);
        map.put("demandAttachment",demandAttachment);


        String servicePrincipal = "";
        if(choice_team.getValue()){
            servicePrincipal = "2";
        }
        if(choice_company.getValue()){
            servicePrincipal ="1";
        }
        if(choice_team.getValue()&&choice_company.getValue()){
            servicePrincipal = "1,2";
        }

        map.put("servicePrincipal",servicePrincipal);


        map.put("budgetPrice",is_bargaining.getValue()?"-1":money.getValue());
        map.put("linkman",contacts_name.getValue());
        map.put("linkmanPhone",contacts_phone.getValue());


        map.put("requirementTypes",5);
        if(!TextUtils.isEmpty(need_remarks.getValue())){
            map.put("note",need_remarks.getValue());
        }
//        map.put("realName", UserOperating.getInstance().getUserInfo().getRealName());
        map.put("userAccount", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
        map.put("userNo","0");
        map.put("companyNo","0");
        map.put("teamNo","0");
        map.put("publishType",UserOperating.getInstance().isCompany()?1:UserOperating.getInstance().isTeam()?2:0);
        switch ((Integer) map.get("publishType")){
            case 1:
                map.put("companyNo",SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO,""));
                map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME,""));
                break;
            case 2:
                map.put("teamNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO,""));
                map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME,""));
                break;

            case 0:
                map.put("userNo",SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO,""));
                map.put("realName",SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME,""));
                break;
        }
        map.put("demandType",1);
        map.put("specifications",need_content.getValue());
        showloading_diag.postValue(1);
//        if(data!=null){
//            map.put("id",data.getId());
//            map.put("createUser",data.getCreateUser());
//            try {
//                data.setDemandTitle(name.getValue());
//                data.setBudgetPrice(is_bargaining.getValue()?-1:Double.parseDouble(money.getValue()));
//                data.setLinkman(contacts_name.getValue());
//                data.setLinkmanPhone(contacts_phone.getValue());
//                data.setNote(need_remarks.getValue());
//                data.setSpecifications(need_content.getValue());
//                data.setCategoryFirstName(map.get("categoryFirstName").toString());
//                data.setCategorySecondName(map.get("categorySecondName").toString());
//                data.setCategoryThirdName(map.get("categoryThirdName").toString());
//                data.setServicePrincipal(map.get("servicePrincipal").toString());
//                data.setCategoryFirstId(map.get("categoryFirstId").toString());
//                data.setCategorySecondId(map.get("categorySecondId").toString());
//                data.setCategoryThirdId(map.get("categoryThirdId").toString());
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//            APIManager.getInstance().getNeedAPI().updateNeedMessage(map).enqueue(new Callback<BaseEntity<Object>>() {
//                @Override
//                public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
//                    if(response!=null&&response.body()!=null) {
//                        showloading_diag.postValue(3);
//                    }else{
//                        showloading_diag.postValue(2);
//                        toast_message.postValue(response.message());
//                    }
//
//                }
//
//                @Override
//                public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
//                    showloading_diag.postValue(2);
//                    toast_message.postValue(t.getMessage());
//
//                }
//            });
//            return;
//
//        }

        APIManager.getInstance().getNeedAPI().publishNeedMessage(map).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {

                if(response!=null&&response.body()!=null) {
                    showloading_diag.postValue(3);
                }else{
                    showloading_diag.postValue(2);
                    toast_message.postValue(response.message());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                showloading_diag.postValue(2);
                toast_message.postValue(t.getMessage());

            }
        });


    }

    /**
     * 选择服务类型
     */
    public void getService_class(){
        if(ldServiceType.getValue()!=null&&ldServiceType.getValue().size()>0){
            ldServiceType.postValue(ldServiceType.getValue());
            return;
        }
        showloading_diag.postValue(1);
        EnterpriseAPIManager.getInstance().getEnterpriseAPI().getServiceCategoryMeasureOption().enqueue(new Callback<BaseEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>> call, Response<BaseEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>> response) {
                showloading_diag.postValue(2);
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                       ldServiceType.postValue(response.body().getData());
                } else {
                    toast_message.postValue(response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>> call, Throwable t) {
                showloading_diag.postValue(2);
            }
        });
    }

    public void setdata(){
        if(!TextUtils.isEmpty(data.demandTitle)){
            name.postValue(data.demandTitle);
        }
        StringBuilder builder = new StringBuilder();
        if(!TextUtils.isEmpty(data.categoryFirstName)){
            mServiceFirstname = data.categoryFirstName;
            builder.append(mServiceFirstname);
        }
        if(!TextUtils.isEmpty(data.categorySecondName)){
            mServiceSecondname = data.categorySecondName;
            builder.append("-").append(mServiceSecondname);
        }
        if(!TextUtils.isEmpty(data.categoryThirdName)){
            mServiceThirdname = data.categoryThirdName;
            builder.append("-").append(mServiceThirdname);
        }
        if(!TextUtils.isEmpty(builder.toString())){
            service_class.postValue(builder.toString());
        }

        if(!TextUtils.isEmpty(data.categoryFirstId)){
            mServiceFirstNo = data.categoryFirstId;
        }
//        if(!TextUtils.isEmpty(data.categorySecondId)){
//            mServiceSecondNo = data.categorySecondId;
//        }
//        if(!TextUtils.isEmpty(data.categoryThirdId)){
//            mServiceThirdNo = data.categoryThirdId;
//        }
        if(!TextUtils.isEmpty(data.servicePrincipal)){
            choice_team.postValue(data.servicePrincipal.indexOf("2")>-1);
            choice_company.postValue(data.servicePrincipal.indexOf("1")>-1);
        }

        if(data.getBudgetPrice()>0){
            money.postValue(PointUtils.price(data.getBudgetPrice()));
            is_bargaining.postValue(false);
        }else{
            is_bargaining.postValue(true);
        }

        if(!TextUtils.isEmpty(data.linkMan)){
            contacts_name.postValue(data.linkMan);
        }
        if(!TextUtils.isEmpty(data.getLinkmanPhone())){
            contacts_phone.postValue(data.getLinkmanPhone());
        }
        if(!TextUtils.isEmpty(data.specifications)){
            need_content.postValue(data.specifications);
        }
        if(!TextUtils.isEmpty(data.note)){
            need_remarks.postValue(data.note);
        }

    }


    public void getAddressModel(Context context) {
        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    MToast.showToast(context, "网络连接超时，请检查网络");
                    return;
                }
                if (response.body().getCode().equals("200"))
                    ldServiceCity.postValue(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void getPatentTypeOption() {
        List<IpPickSelectEntity> list = new ArrayList<>();
        IpPickSelectEntity entity = new IpPickSelectEntity();
        entity.setName("不需要发票");
        entity.setId("0");
        list.add(entity);
        entity = new IpPickSelectEntity();
        entity.setName("增值税普通发票");
        entity.setId("1");
        list.add(entity);
        entity = new IpPickSelectEntity();
        entity.setName("增值税专用发票");
        entity.setId("2");
        list.add(entity);
        mBillTypeListLiveData.postValue(list);

    }


    /****
     * 上传单张图片
     * @param file
     * @param completeNum
     */
    public void uploadSingleImage(Context context, File file, int completeNum, boolean isEnd) {
        Map<String, RequestBody> photos = new HashMap<>(1);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFileV1(photos).enqueue(new Callback<BaseEntity<List<String>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<String>>> call, Response<BaseEntity<List<String>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null && response.body().getData().size() != 0) {
                        stringLiveData.postValue(response.body().getData().get(0));
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<String>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
